﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Bomb : MonoBehaviour
{

    private Animator anim;
    private Collider2D coll;
    private Rigidbody2D rb;
    public float startTime;
    public float waitTime;
    public float bombForce;

    public float damage = 3;

    [Header("Check")]
    public float radius;
    public LayerMask targetLayer;
    // Start is called before the first frame update
    void Start()
    {
        anim = GetComponent<Animator>();
        coll = GetComponent<Collider2D>();
        rb = GetComponent<Rigidbody2D>();
        startTime = Time.time;
    }

    // Update is called once per frame
    void Update()
    {
        if (!anim.GetCurrentAnimatorStateInfo(0).IsName("bomb_off"))  //获取指定图层指定动画是否播放
        {
            if (Time.time > startTime + waitTime)
            {
                anim.Play("bomb_explotion"); //执行动画
            }
        }

    }

    //在界面上画图形
    //Unity自动调用，只在预览时才会调用
    public void OnDrawGizmos()
    {
        Gizmos.DrawWireSphere(transform.position, radius);
    }

    //爆炸，动画方法
    public void Explotion()
    {
        coll.enabled = false;  //关闭碰撞体组件
        rb.gravityScale = 0; //取消刚体重力
        //检测半径内指定图层的所有碰撞体
        Collider2D[] aroundObjects = Physics2D.OverlapCircleAll(transform.position, radius, targetLayer);

        foreach (var item in aroundObjects)
        {
            if (item.gameObject.CompareTag("noBomb"))
            {
                continue;
            }
            Vector3 pos = transform.position - item.transform.position;

            //给刚体添加力，Impulse 瞬时的脉冲力
            item.GetComponent<Rigidbody2D>().AddForce((-pos + Vector3.up) * bombForce, ForceMode2D.Impulse);

            //将周围的炸弹从新点燃
            if (item.CompareTag("Bomb") && item.GetComponent<Animator>().GetCurrentAnimatorStateInfo(0).IsName("bomb_off"))
            {
                item.GetComponent<Bomb>().TrunOn();
            }

            if (item.CompareTag("Player"))
            {
                item.GetComponent<IDamageble>().GetHit(damage);
            }
        }
    }

    public void TrunOff()
    {
        anim.Play("bomb_off");
        gameObject.layer = LayerMask.NameToLayer("NPC"); //修改图层
    }

    public void TrunOn()
    {
        startTime = Time.time;
        anim.Play("bomb_on");
        gameObject.layer = LayerMask.NameToLayer("Bomb"); //修改图层
    }

    //Enter 进入检测
    // public void OnTriggerStay2D(Collider2D collision)
    // {
    //     if (!collision.gameObject.CompareTag("plat"))
    //     {
    //         Vector3 pos = transform.position - collision.transform.position;
    //         collision.GetComponent<Rigidbody2D>().AddForce((-pos + Vector3.up) * bombForce, ForceMode2D.Impulse);
    //     }
    // }

    public void DestroyBomb()
    {
        Destroy(gameObject);
    }
}
